<?php
// +—————————————————————————————————————————————————————————————————————
// | Created by Yunbao
// +—————————————————————————————————————————————————————————————————————
// | Copyright (c) 2013~2022 http://www.yunbaokj.com All rights reserved.
// +—————————————————————————————————————————————————————————————————————
// | Author: https://gitee.com/yunbaokeji
// +—————————————————————————————————————————————————————————————————————
// | Date: 2022-04-30
// +—————————————————————————————————————————————————————————————————————

    use think\Db;
    use cmf\lib\Storage;
	
	
	
	
    // 应用公共文件
    error_reporting(E_ERROR | E_WARNING | E_PARSE);

    require_once dirname(__FILE__).'/redis.php';
	
	
	/**
	 * 获取当前登录的管事员id
	 * @return int
	 */
	function get_current_admin_id(){
		return session('ADMIN_ID');
	}

    /* 去除NULL 判断空处理 主要针对字符串类型*/
	function checkNull($checkstr){
        $checkstr=trim($checkstr);
		$checkstr=urldecode($checkstr);

		if( strstr($checkstr,'null') || (!$checkstr && $checkstr!=0 ) ){
			$str='';
		}else{
			$str=$checkstr;
		}
		$str=htmlspecialchars($str);
		return $str;	
	}
    
    /* 检验手机号 */
	function checkMobile($mobile){
		$ismobile = preg_match("/^1[3|4|5|6|7|8|9]\d{9}$/",$mobile);
		if($ismobile){
			return 1;
		}
        
        return 0;
		
	}
    
	/* 去除emoji表情 */
	function filterEmoji($str){
		$str = preg_replace_callback(
			'/./u',
			function (array $match) {
				return strlen($match[0]) >= 4 ? '' : $match[0];
			},
			$str);
		return $str;
	}
    
    /**
	 * 转化数据库保存的文件路径，为可以访问的url
	 */
	function get_upload_path($file){


        if($file==''){
            return $file;
        }

        $configpri=getConfigPri();

		if(strpos($file,"http")===0){
			//将字符串分隔
			$file_arr=explode('%@%cloudtype=',$file);

			$cloudtype=$file_arr['1'];
			$file=$file_arr['0'];

			if(!isset($cloudtype)){
				return html_entity_decode($file);
			}

			if($cloudtype==1){ //存储方式为七牛
				return html_entity_decode($file);
			}else{
				return html_entity_decode($file);
			}


		}else if(strpos($file,"/")===0){

			$filepath= cmf_get_domain().$file;
			return $filepath;
		}else{

			//将字符串分隔
			$file_arr=explode('%@%cloudtype=',$file);

			$cloudtype=$file_arr['1'];
			$file=$file_arr['0'];
            
            
			if($cloudtype==1){ //七牛存储
				$space_host=$configpri['qiniu_protocol']."://".$configpri['qiniu_domain']."/";
			}else{
				$space_host="http://";
			}
			
			$filepath=$space_host.$file;

			if(!isset($cloudtype)){
				return html_entity_decode($filepath);
			}

			if($cloudtype==2 && $configpri['tx_private_signature']){ //腾讯云存储 且 需要签名验证
				
				return setTxUrl(html_entity_decode($filepath)); //腾讯云存储为私有读写时需要调用该方法获取签名验证
			}else{
				return html_entity_decode($filepath);
			}
		}
	}

    /* 公共配置 */
    function getConfigPub() {
        $key='getConfigPub';
        $config=getcaches($key);
		$config=false;
        if(!$config){
            $config= cmf_get_option('site_info', $options);
            setcaches($key,$config);
        }

        return 	$config;
    }		


    /* 获取私密配置 */
	function getConfigPri() {
		$key='getConfigPri';
		$config=getcaches($key);
		$config=false;
		if(!$config){
			
            $config=cmf_get_option('configpri');
			setcaches($key,$config);
		}
        
        
		return 	$config;
	}

	/* 判断token */
	function checkToken($uid,$token) {
        if($uid<1 || $token==''){
            return 700;
        }
        $key="token_".$uid;
		$userinfo=getCache($key);
		if(!$userinfo){
			$userinfo=Db::name('user_token')
					->field('token,expire_time')
					->where(['user_id'=>$uid])
					->find();
            if($userinfo){
                setCache($key,$userinfo);
            }
		}

		if(!$userinfo || $userinfo['token']!=$token || $userinfo['expire_time']<time()){
			return 700;				
		}
		
	
        
        return 	0;				
		
	}
    
	/* 用户基本信息 */

    function getUserInfo($uid) {
        $info= Db::name("user")
			->field("id,user_nicename,avatar,avatar_thumb,sex,signature,province,city,birthday,user_status")
			->where("id='{$uid}'")
			->find();
		if($info){
			$info['avatar']=get_upload_path($info['avatar']);
			$info['avatar_thumb']=get_upload_path($info['avatar_thumb']);

		}
				
		return 	$info;		
    }	
    


    function getLength($time,$type=0){

		if(!$time){
			return (string)$time;
		}

	    $value = array(
	      "years"   => 0,
	      "days"    => 0,
	      "hours"   => 0,
	      "minutes" => 0,
	      "seconds" => 0
	    );
	    
	    if($time >= 31556926){
	      $value["years"] = floor($time/31556926);
	      $time = ($time%31556926);
	    }
	    if($time >= 86400){
	      $value["days"] = floor($time/86400);
	      $time = ($time%86400);
	    }
	    if($time >= 3600){
	      $value["hours"] = floor($time/3600);
	      $time = ($time%3600);
	    }
	    if($time >= 60){
	      $value["minutes"] = floor($time/60);
	      $time = ($time%60);
	    }
	    $value["seconds"] = floor($time);

	    if($value['years']){
	    	if($type==1&&$value['years']<10){
	    		$value['years']='0'.$value['years'];
	    	}
	    }

	    if($value['days']){
	    	if($type==1&&$value['days']<10){
	    		$value['days']='0'.$value['days'];
	    	}
	    }

	    if($value['hours']){
	    	if($type==1&&$value['hours']<10){
	    		$value['hours']='0'.$value['hours'];
	    	}
	    }

	    if($value['minutes']){
	    	if($type==1&&$value['minutes']<10){
	    		$value['minutes']='0'.$value['minutes'];
	    	}
	    }

	    if($value['seconds']){
	    	if($type==1&&$value['seconds']<10){
	    		$value['seconds']='0'.$value['seconds'];
	    	}
	    }

	    if($value['years']){
	    	$t=$value["years"] ."年".$value["days"] ."天". $value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
	    }else if($value['days']){
	    	$t=$value["days"] ."天". $value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
	    }else if($value['hours']){
	    	$t=$value["hours"] ."小时". $value["minutes"] ."分".$value["seconds"]."秒";
	    }else if($value['minutes']){
	    	$t=$value["minutes"] ."分".$value["seconds"]."秒";
	    }else if($value['seconds']){
	    	$t=$value["seconds"]."秒";
	    }
	    
	    return $t;

	}


	/**导出Excel 表格
    * @param $expTitle 名称
    * @param $expCellName 参数
    * @param $expTableData 内容
    * @throws \PHPExcel_Exception
    * @throws \PHPExcel_Reader_Exception
    */
	function exportExcel($expTitle,$expCellName,$expTableData,$cellName){

		//$xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
		$xlsTitle =  $expTitle;//文件名称
		$fileName = $xlsTitle.'_'.date('YmdHis');//or $xlsTitle 文件名称可根据自己情况设定
		$cellNum = count($expCellName);
		$dataNum = count($expTableData);
		
        $path= CMF_ROOT.'sdk/PHPExcel/';
        require_once( $path ."PHPExcel.php");
        
		$objPHPExcel = new \PHPExcel();
		$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(10);
		for($i=0;$i<$cellNum;$i++){
			$objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'1', $expCellName[$i][1]);
		}
		for($i=0;$i<$dataNum;$i++){
			for($j=0;$j<$cellNum;$j++){
				$objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+2), filterEmoji( $expTableData[$i][$expCellName[$j][0]] ) );
			}
		}
		header('pragma:public');
		header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xlsx"');
		header("Content-Disposition:attachment;filename={$fileName}.xlsx");//attachment新窗口打印inline本窗口打印
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');//Excel5为xls格式，excel2007为xlsx格式
		$objWriter->save('php://output');
		exit;
	}
	
	
	function get_file_suffix($file_name, $allow_type = array()){

      $fnarray=explode('.', $file_name);

      $file_suffix = strtolower(end($fnarray));


      if (empty($allow_type)){
        return true;
      }else{
        if (in_array($file_suffix, $allow_type)){
			return true;
        }else{
			return false;
        }
      }
    }
	
	/* 
    单文件云存储
    files  单个文件上传信息(包含键值)   $files['file']=$_FILES["file"]
    type  文件类型 img图片 video视频 music音乐
    
	 */
	function adminUploadFilesBF($files='',$type="video"){

		$rs=array('code'=>1000,'data'=>[],'msg'=>'上传失败');
		
		
		
		//获取后台上传配置
		$configpri=getConfigPri();
		if($configpri['cloudtype']==1){  //七牛云存储
			require_once CMF_ROOT.'sdk/qiniu/autoload.php';

			// 需要填写你的 Access Key 和 Secret Key
			$accessKey = $configpri['qiniu_accesskey'];
			$secretKey = $configpri['qiniu_secretkey'];
			$bucket = $configpri['qiniu_bucket'];
			$qiniu_domain_url = $configpri['qiniu_domain_url'];

			// 构建鉴权对象
			$auth = new \Qiniu\Auth($accessKey, $secretKey);

			// 生成上传 Token
			$token = $auth->uploadToken($bucket);

			// 要上传文件的本地路径
			$filePath = $files['file']['tmp_name'];

			// 上传到七牛后保存的文件名
			$ext=strtolower(pathinfo($files['file']['name'], PATHINFO_EXTENSION));
			$key = date('Ymd').'/'.uniqid().'.'.$ext;

			// 初始化 UploadManager 对象并进行文件的上传。
			$uploadMgr = new \Qiniu\Storage\UploadManager();
			
			// 调用 UploadManager 的 putFile 方法进行文件的上传。
			list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);
			
			if($err !== null){
				$rs['msg']=$err->getResponse()->error;
				return $rs;
			}

			$url=$key;
			$url_p=$qiniu_domain_url.$key;
			
		}
		
		$rs['code']=0;
		$rs['data']['url']=$url;
		$rs['data']['url_p']=$url_p;

		return $rs;
	}


	/* 
    单文件云存储
    files  单个文件上传信息(包含键值)   $files['file']=$_FILES["file"]
    type  文件类型 img图片 video视频 music音乐
    
 */
function adminUploadFiles($files='',$type="video"){

	$name=$files["file"]['name'];
    $pathinfo=pathinfo($name);
    
    if(!isset($pathinfo['extension'])){
        $files["file"]['name']=$name.'.jpg';
    }

    $rs=array('code'=>1000,'data'=>[],'msg'=>'上传失败');
	//获取后台上传配置
	$configpri=getConfigPri();

	$cloudtype=$configpri['cloudtype'];

	if($cloudtype==1){  //七牛云存储
		require_once CMF_ROOT.'sdk/qiniu/autoload.php';

        // 需要填写你的 Access Key 和 Secret Key
        $accessKey = $configpri['qiniu_accesskey'];
        $secretKey = $configpri['qiniu_secretkey'];
        $bucket = $configpri['qiniu_bucket'];
        /* $qiniu_domain_url = $configpri['qiniu_domain_url']; */
        $qiniu_domain_url =  $configpri['qiniu_protocol']."://".$configpri['qiniu_domain']."/";

        // 构建鉴权对象
        $auth = new \Qiniu\Auth($accessKey, $secretKey);

        // 生成上传 Token
        $token = $auth->uploadToken($bucket);

        // 要上传文件的本地路径
        $filePath = $files['file']['tmp_name'];

        // 上传到七牛后保存的文件名
        $ext=strtolower(pathinfo($files['file']['name'], PATHINFO_EXTENSION));
        $key = date('Ymd').'/'.uniqid().'.'.$ext;

        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new \Qiniu\Storage\UploadManager();
        
        // 调用 UploadManager 的 putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile($token, $key, $filePath);

        
        
        if($err !== null){
            $rs['msg']=$err->getResponse()->error;
            return $rs;
        }

        $url=$qiniu_domain_url.$key;
        $url_p=$key;


	}
    
    $rs['code']=0;
    $rs['data']['url']=$url_p;
    $rs['data']['url_p']=setCloudType($url_p); //设置存储方式
    $rs['data']['url_c']=$url;

    $tx_private_signature=$configpri['tx_private_signature'];

    if($cloudtype==2 && $tx_private_signature){ //腾讯存储桶为私有读 需要进行文件验证签名
    	$rs['data']['url_c']=setTxUrl($url_p); //签名地址
    }

    //return $rs;

    //同步Upload.php返回格式
    return [
        'filepath'    => $rs['data']['url_p'], //带存储方式的【存储用】
        "name"        => '',
        'id'          => time().rand(1,99),
        'preview_url' =>$rs['data']['url_c'], //带签名的【展示用】
        'url'         => $rs['data']['url_c'],
        'code'		  =>0
    ];


	
}

	
	/* 数字格式化 */
	function NumberFormat($num){
		if($num<10000){

		}else if($num<1000000){
			$num=round($num/10000,2).'万';
		}else if($num<100000000){
			$num=round($num/10000,1).'万';
		}else if($num<10000000000){
			$num=round($num/100000000,2).'亿';
		}else{
			$num=round($num/100000000,1).'亿';
		}
		return $num;
	}
	
	/* 生成邀请码 */
	function createCode(){
		$code = 'ABCDEFGHIJKLMNPQRSTUVWXYZ';
		$rand = $code[rand(0,25)]
			.strtoupper(dechex(date('m')))
			.date('d').substr(time(),-5)
			.substr(microtime(),2,5)
			.sprintf('%02d',rand(0,99));
		for(
			$a = md5( $rand, true ),
			$s = '123456789ABCDEFGHIJKLMNPQRSTUV',
			$d = '',
			$f = 0;
			$f < 6;
			$g = ord( $a[ $f ] ),
			$d .= $s[ ( $g ^ ord( $a[ $f + 6 ] ) ) - $g & 0x1F ],
			$f++
		);
		if(mb_strlen($d)==6){
			$oneinfo=Db::name("user")->field("id")->where("code='{$d}'")->find();
			if(!$oneinfo){
				return $d;
			}
		}
		
        $d=createCode();
		return $d;
	}
	
	function m_s($a){
		return $a;
		$url=$_SERVER['HTTP_HOST'];
		$domain=cmf_get_domain();
		$domain=str_replace("https://", '', $domain);
		$domain=str_replace("http://", '', $domain);
		if($url==$domain){
			$l=strlen($a);
			$sl=$l-6;
			$s='';
			for($i=0;$i<$sl;$i++){
				$s.='*';
			}
			$rs=substr_replace($a,$s,3,$sl);
			return $rs;
		}
		return $a;
	}
	


	//为文件拼接存储方式,方便get_upload_path做签名处理

	function setCloudType($url){
		$configpri=getConfigPri();
		$cloudtype=$configpri['cloudtype'];

		//file_put_contents("zzza.txt", $url);

		$url=$url."%@%cloudtype=".$cloudtype;

		//file_put_contents("zzz.txt", $url);
		return $url;
	}



    //获取粉丝数量
    function getFans($uid){
    	$count=Db::name("user_attention")->where("touid={$uid}")->count();
    	return $count;
    }



	//判断用户是否注销
	function checkIsDestroy($uid){
		$user_status=Db::name("user")->where("id={$uid}")->value('user_status');
		if($user_status==3){
			return 1;
		}

		return 0;
	}
	

	
	//身份证检测
	function checkCardNo($cardno){
		$preg='/^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/';
		$isok=preg_match($preg, $cardno);
		if($isok){
			return 1;
		}else{
			return 0;
		}
	}






	/* ip限定 */
	function ip_limit(){
		$configpri=getConfigPri();
		if($configpri['iplimit_switch']==0){
			return 0;
		}
		$date = date("Ymd");
		$ip= ip2long($_SERVER["REMOTE_ADDR"]);
		
		$isexist=Db::name("getcode_limit_ip")
				->field("ip,date,times")
				->where("ip={$ip}") 
				->find();

		if(!$isexist){
			$data=array(
				"ip" => $ip,
				"date" => $date,
				"times" => 1,
			);
			$isexist=Db::name("getcode_limit_ip")->insert($data);
			return 0;
		}elseif($date == $isexist['date'] && $isexist['times'] >= $configpri['iplimit_times'] ){
			return 1;
		}else{
			if($date == $isexist['date']){
				$isexist=Db::name("getcode_limit_ip")
						->where("ip={$ip}")
						->setInc("times",1);

				return 0;
			}else{
				$isexist=Db::name("getcode_limit_ip")
						->where("ip={$ip}") 
						->update(array('date'=> $date ,'times'=>1));
				return 0;
			}
		}	
	}

	/* 随机数 */
	function random($length = 6 , $numeric = 0) {
		PHP_VERSION < '4.2.0' && mt_srand((double)microtime() * 1000000);
		if($numeric) {
			$hash = sprintf('%0'.$length.'d', mt_rand(0, pow(10, $length) - 1));
		} else {
			$hash = '';
			$chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789abcdefghjkmnpqrstuvwxyz';
			$max = strlen($chars) - 1;
			for($i = 0; $i < $length; $i++) {
				$hash .= $chars[mt_rand(0, $max)];
			}
		}
		return $hash;
	}

	/* 发送验证码 -- 阿里云 */
	function sendCode($mobile,$code){
        
		$rs = array('code' => 0, 'msg' => '', 'info' => array());
        
		$config = getConfigPri();
        
        if(!$config['sendcode_switch']){
            $rs['code']=667;
			$rs['msg']='123456';
            return $rs;
        }
        

		$rs=sendCodeByAli($mobile,$code);


		return $rs;
	}

	//阿里云短信
	function sendCodeByAli($mobile,$code){
		$rs = array('code' => 0, 'msg' => '', 'info' => array());
        
        $configpri = getConfigPri();
		
		require_once CMF_ROOT.'sdk/aliyunsms/AliSmsApi.php';
        
		$config  = array(
			'accessKeyId' =>$configpri['aly_keydi'], 
			'accessKeySecret' =>$configpri['aly_secret'], 
			'PhoneNumbers' => $mobile, 
			'SignName' => $configpri['aly_signName'], 
			'TemplateCode' => $configpri['aly_templateCode'], 
			'TemplateParam' => array("code"=>$code) 
		);

		 
		$go = new \AliSmsApi($config);
		$result = $go->send_sms();
		file_put_contents(CMF_ROOT.'log/sendCode_aly_'.date('Y-m-d').'.txt',date('Y-m-d H:i:s').' 提交参数信息 result:'.json_encode($result)."\r\n",FILE_APPEND);
		
        if($result == NULL ) {
            $rs['code']=1002;
			$rs['msg']="发送失败";
            return $rs;
        }
		if($result['Code']!='OK') {
            //TODO 添加错误处理逻辑
            $rs['code']=1002;
			$rs['msg']="获取失败";
            return $rs;
        }
		return $rs;
	}




	/* 检测用户是否存在 */
    function checkUser($where){
        if(!$where){
            return 0;
        }

        $isexist=Db::name('user')->field('id')->where($where)->find();
        
        if($isexist){
            return 1;
        }
        
        return 0;
    }
	
	/* 管理员操作日志 */
    function setAdminLog($action){
        $data=array(
            'adminid'=>session('ADMIN_ID'),
            'admin'=>session('name'),
            'action'=>$action,
            'ip'=>ip2long(get_client_ip(0,true)),
            'addtime'=>time(),
        );
        
        Db::name("admin_log")->insert($data);
        return !0;
    }
